const Service = require('egg').Service;

class BannerService extends Service {
  // 创建轮播图
  async create(bannerData) {
    const { ctx } = this;

    // 检查显示顺序是否重复
    if (bannerData.display_order) {
      const existingBanner = await ctx.model.Banner.findOne({
        where: { display_order: bannerData.display_order }
      });
      if (existingBanner) {
        throw new Error('该显示顺序已被占用');
      }
    }

    const banner = await ctx.model.Banner.create({
      ...bannerData,
      created_at: new Date(),
      updated_at: new Date()
    });

    return banner;
  }

  // 获取轮播图列表（分页）
  async getBanners(query) {
    const { ctx } = this;
    const { page = 1, pageSize = 10, is_active, title } = query;

    const where = {};
    if (is_active !== undefined) {
      where.is_active = parseInt(is_active);
    }
    if (title) {
      // 修复：使用正确的 Sequelize 操作符
      where.title = {
        [this.app.Sequelize.Op.like]: `%${title}%`
      };
    }

    const options = {
      where,
      limit: parseInt(pageSize),
      offset: (parseInt(page) - 1) * parseInt(pageSize),
      order: [['display_order', 'ASC'], ['created_at', 'DESC']]
    };

    const { count, rows } = await ctx.model.Banner.findAndCountAll(options);

    return {
      list: rows,
      pagination: {
        page: parseInt(page),
        pageSize: parseInt(pageSize),
        total: count,
        totalPages: Math.ceil(count / pageSize)
      }
    };
  }

  // 根据ID获取轮播图详情
  async getBannerById(bannerId) {
    const { ctx } = this;

    const banner = await ctx.model.Banner.findByPk(bannerId);

    if (!banner) {
      throw new Error('轮播图不存在');
    }

    return banner;
  }

  // 更新轮播图信息
  async updateBanner(bannerId, updateData) {
    const { ctx } = this;

    // 检查轮播图是否存在
    const banner = await ctx.model.Banner.findByPk(bannerId);
    if (!banner) {
      throw new Error('轮播图不存在');
    }

    // 如果更新显示顺序，检查是否重复
    if (updateData.display_order && updateData.display_order !== banner.display_order) {
      const existingBanner = await ctx.model.Banner.findOne({
        where: { display_order: updateData.display_order }
      });
      if (existingBanner) {
        throw new Error('该显示顺序已被占用');
      }
    }

    // 更新轮播图信息
    await banner.update({
      ...updateData,
      updated_at: new Date()
    });

    return banner;
  }

  // 删除轮播图
  async deleteBanner(bannerId) {
    const { ctx } = this;

    const banner = await ctx.model.Banner.findByPk(bannerId);
    if (!banner) {
      throw new Error('轮播图不存在');
    }

    await banner.destroy();
    return true;
  }

  // 获取启用的轮播图（用于前端展示）
  async getActiveBanners() {
    const { ctx } = this;

    const banners = await ctx.model.Banner.findAll({
      where: { is_active: 1 },
      order: [['display_order', 'ASC'], ['created_at', 'DESC']],
      attributes: [
        'banner_id',
        'image_url',
        'link_url',
        'title',
        'display_order'
      ]
    });

    return banners;
  }

  // 切换轮播图状态
  async toggleBannerStatus(bannerId) {
    const { ctx } = this;

    const banner = await ctx.model.Banner.findByPk(bannerId);
    if (!banner) {
      throw new Error('轮播图不存在');
    }

    const newStatus = banner.is_active === 1 ? 0 : 1;
    await banner.update({
      is_active: newStatus,
      updated_at: new Date()
    });

    return {
      banner_id: banner.banner_id,
      is_active: newStatus
    };
  }

  // 批量更新轮播图顺序
  async updateBannerOrders(orders) {
    const { ctx } = this;

    const results = {
      success: 0,
      failed: 0,
      errors: []
    };

    for (const order of orders) {
      try {
        const { banner_id, display_order } = order;

        const banner = await ctx.model.Banner.findByPk(banner_id);
        if (!banner) {
          throw new Error('轮播图不存在');
        }

        // 修复：使用正确的 Sequelize 操作符
        const existingBanner = await ctx.model.Banner.findOne({
          where: {
            display_order,
            banner_id: { [this.app.Sequelize.Op.ne]: banner_id }
          }
        });
        if (existingBanner) {
          throw new Error(`显示顺序 ${display_order} 已被占用`);
        }

        await banner.update({
          display_order,
          updated_at: new Date()
        });

        results.success++;
      } catch (error) {
        results.failed++;
        results.errors.push(`轮播图ID ${order.banner_id}: ${error.message}`);
      }
    }

    return results;
  }

  // 获取轮播图统计信息
  async getBannerStats() {
    const { ctx } = this;

    const total = await ctx.model.Banner.count();
    const active = await ctx.model.Banner.count({
      where: { is_active: 1 }
    });
    const inactive = await ctx.model.Banner.count({
      where: { is_active: 0 }
    });

    return {
      total,
      active,
      inactive
    };
  }
}

module.exports = BannerService;